<template>
	<view class="flex align-center text-right">
		<uni-easyinput v-model="inputValue" type="digit" :inputBorder="false" :placeholder="data.placeholder" :clearable="props.data.clearIcon" @blur="onBlur" @clear="onClear" />
		<text v-if="data.rightSlots" class="ml-5 pr-5">{{ data.rightSlots }}</text>
	</view>
</template>

<script setup lang="ts">
import { watch, ref } from 'vue'
import { isEmpty } from '@/assets/js/utils'

const props = defineProps({
	//表单组件参数
	data: {
		type: Object,
		required: true
	},
	modelValue: {}
})

watch(props, (val: any) => {
	if (val.modelValue) {
		if (props.data.isCent) {
			inputValue.value = Number(val.modelValue) / 100
		} else {
			inputValue.value = val.modelValue
		}
	} else {
		inputValue.value = ''
	}
})

const inputValue = ref()
//修改双向绑定值
const emit = defineEmits(['update:modelValue'])

const onBlur = (event: any) => {
	let value = event.detail.value
	if (isNaN(value)) {
		inputValue.value = props.data.min
		return
	}
	value = +value
	if (value > props.data.max) {
		value = props.data.max
	} else if (value < props.data.min) {
		value = props.data.min
	}
	const scale = getDecimalScale()
	inputValue.value = value.toFixed(String(scale).length - 1)
	if (props.data.isCent) {
		emit('update:modelValue', +inputValue.value * 100)
	} else {
		emit('update:modelValue', +inputValue.value)
	}
}

const onClear = () => {
	inputValue.value = ''
	emit('update:modelValue', '')
}

const getDecimalScale = () => {
	let scale = 1
	// 浮点型
	if (~~props.data.step !== props.data.step) {
		scale = Math.pow(10, String(props.data.step).split('.')[1].length)
	}
	return scale
}
</script>

<style lang="scss">
.form-number-input {
	text-align: right;
}
</style>
